/* -------------------------------------- 

     Cherrypy webapp skeleton frontend

     License: LGPL
     Authors: saaj (mail@saaj.me)

   -------------------------------------- */

/**
 * Abstract editor view
 */
qx.Class.define("webapp.view.AbstractEditor", {

	extend : qx.ui.window.Window,
  type   : "abstract",

  properties : {
    
    model : {
      apply    : "_applyModel",
      init     : null,
      nullable : true
    }
    
  },
  
  construct : function()
  {
  	this._windowHeading = this._getFormHeading();

    this.base(arguments, this._windowHeading.caption, this._windowHeading.icon);

    this.set({
      layout       : new qx.ui.layout.VBox(),
      showMinimize : false,
      showMaximize : false
    });
    this.addListener("appear", this.center, this);
    
    this._form       = new qx.ui.form.Form();
    this._controller = new qx.data.controller.Form(null, this._form);
  },

  destruct : function()
  {
    this._disposeObjects("_form", "_controller");
  },
  
  members : {

  	_form          : null,
  	_controller    : null,
  	_windowHeading : null,


  	_getFormHeading : function()
  	{
      throw new Error("Must be overriden in descendent class");
      
      return {
        caption : null,
        icon    : null
      };
  	},
    
  	_onModelLoaded : function()
  	{
      this._controller.setModel(this.getModel().getFormModel());
  	},
    
    _createButtons : function()
    {
      var okButton = new qx.ui.form.Button(this.tr("OK"));
      okButton.setWidth(70);
      okButton.addListener("execute", this._onOk, this);
      this._form.addButton(okButton);

      var cancelButton = new qx.ui.form.Button(this.tr("Cancel"));
      cancelButton.setWidth(70);
      cancelButton.addListener("execute", this._onCancel, this);
      this._form.addButton(cancelButton);
    },
    
  	_createForm : function()
  	{
      this._createButtons();
  	},

  	_onOk : function()
  	{
  	  if(this._form.validate())
  	  {
        this.getModel().save();
        this.hide();
      }
  	},

  	_onCancel : function()
  	{
      this.close();
  	},

  	_renderForm : function()
  	{
  		var renderer = new qx.ui.form.renderer.Single(this._form);
  		renderer.getLayout().setColumnFlex(0, 0);
  		renderer.getLayout().setColumnFlex(1, 1);

      this.add(renderer, {flex : 1});
  	},
    
    _applyModel : function(newModel, oldModel)
    {
      if(oldModel)
      {
        oldModel.removeListener("loaded",  this._onModelLoaded, this);
      }
      if(newModel)
      {
        newModel.addListener("loaded",  this._onModelLoaded, this);
      }
  
      this._createForm();
      this._renderForm();
    },
    
    load : function(item)
    {
      this._form.reset();
      this.getModel().load(item);
    }
    
  }

});